package com.assetmanage.controller;

import com.assetmanage.model.Department;
import com.assetmanage.service.DepartmentService;
import com.assetmanage.service.impl.DepartmentServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

@WebServlet("/api/departments")
public class DepartmentServlet extends BaseServlet {
    private DepartmentService departmentService = new DepartmentServiceImpl();

    // 获取所有部门
    public void getAllDepartments(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        writeSuccess(resp, departmentService.getAllDepartments());
    }

    // 根据ID获取部门
    public void getDepartmentById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String depId = req.getParameter("depId");
        if (depId == null) {
            writeError(resp, "部门ID不能为空");
            return;
        }
        Department department = departmentService.getDepartmentById(depId);
        if (department != null) {
            writeSuccess(resp, department);
        } else {
            writeError(resp, "部门不存在");
        }
    }

    // 添加部门
    public void addDepartment(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = req.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        }
        
        Department department = GSON.fromJson(sb.toString(), Department.class);
        if (departmentService.addDepartment(department)) {
            writeSuccess(resp, null);
        } else {
            writeError(resp, "添加部门失败");
        }
    }

    // 更新部门
    public void updateDepartment(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = req.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        }
        
        Department department = GSON.fromJson(sb.toString(), Department.class);
        if (departmentService.updateDepartment(department)) {
            writeSuccess(resp, null);
        } else {
            writeError(resp, "更新部门失败");
        }
    }

    // 删除部门
    public void deleteDepartment(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String depId = req.getParameter("depId");
        if (depId == null) {
            writeError(resp, "部门ID不能为空");
            return;
        }
        if (departmentService.deleteDepartment(depId)) {
            writeSuccess(resp, null);
        } else {
            writeError(resp, "删除部门失败");
        }
    }
} 